package com.example.Web_chat.component;

import com.example.Web_chat.mapper.GroupMessageMapper;
import com.example.Web_chat.mapper.UserMapper;
import com.example.Web_chat.model.GroupMessage;
import com.example.Web_chat.model.GroupMessageRequest;
import com.example.Web_chat.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatWebSocketAPI extends TextWebSocketHandler {

    @Autowired
    private GroupMessageMapper messageGroup;

    @Autowired
    private UserMapper userMapper;
    // 用来存储每个群聊 ID 对应的 WebSocket 会话
    private Map<Integer, List<WebSocketSession>> groupSessions = new ConcurrentHashMap<>();
    ObjectMapper objectMapper = new ObjectMapper();

    // --------------------------处理消息-----------------------------
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("接受到消息，开始处理:给前端的" );
        GroupMessageRequest msgReq = objectMapper.readValue(message.getPayload(), GroupMessageRequest.class);

        if (!"groupMessage".equals(msgReq.getType())) {
            return; // 非群聊消息忽略
        }

        Integer groupId = msgReq.getGroupId();
        String content = msgReq.getMessageContent();
        Integer senderId = msgReq.getSenderId();

        // 保存消息到数据库
        GroupMessage newMessage = new GroupMessage();
        newMessage.setGroupId(groupId);
        newMessage.setSenderId(senderId);
        newMessage.setMessageContent(content);
        newMessage.setTimestamp(java.time.LocalDateTime.now());
        messageGroup.sendMessageGroup(newMessage);
        // 构造广播消息
        Map<String, Object> resp = new HashMap<>();
        resp.put("type", "groupMessage");
        User user = userMapper.selectByID(senderId);
        String avatar = user.getAvatar(); // ------头像 ------------------

        resp.put("fromName", "用户" + user.getUsername()); // 或从数据库查询用户名
        resp.put("messageContent", content);
        resp.put("avatarUrl", avatar); // ✅ 添加头像
        String json = objectMapper.writeValueAsString(resp);

        List<WebSocketSession> sessions = groupSessions.get(groupId);
        if (sessions != null) {
            for (WebSocketSession s : sessions) {
                if (s.isOpen()) {
                    s.sendMessage(new TextMessage(json));
                }
            }
        }
    }


    // 处理 WebSocket 会话连接建立
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("群聊会话链接成功: " );
        // 从 URI 中获取参数
        String uri = session.getUri().toString();
        String query = session.getUri().getQuery(); // groupId=23
        Integer groupId = null;

        if (query != null && query.startsWith("groupId=")) {
            groupId = Integer.parseInt(query.split("=")[1]);
        }

        if (groupId == null) {
            session.close(); // 关闭非法连接
            return;
        }

        groupSessions.computeIfAbsent(groupId, k -> new ArrayList<>()).add(session);
        session.getAttributes().put("groupId", groupId); // ✅ 后面需要取出用

    }


    // 处理 WebSocket 会话关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        // 获取群聊ID
        Integer groupId = Integer.parseInt((String) session.getAttributes().get("groupId"));

        // 从群聊会话列表中移除当前会话
        List<WebSocketSession> sessions = groupSessions.get(groupId);
        if (sessions != null) {
            sessions.remove(session);
        }
    }

    // 可以通过某些方式管理 WebSocket 会话，比如将会话保存在某个集合中，按群聊ID进行分组
    private List<WebSocketSession> getSessionsByGroupId(Integer groupId) {
        return groupSessions.get(groupId);
    }
}
